package org.tgcloud.group.service.manager;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tgcloud.group.core.*;
import org.tgcloud.group.entity.SysManagerUser;
import org.tgcloud.group.repository.MjProjectMapper;
import org.tgcloud.group.repository.SysManagerUserMapper;
import org.tgcloud.group.repository.SysRoleMapper;
import org.tgcloud.group.web.controller.dto.user.ManagerAdminUserDTO;

import java.util.*;

/**
 * @author: zhy
 * @create: 2023-07-24 13:44
 * @description:
 */
@Service
public class ManagerUserService {

    @Autowired
    private PasswordHelper passwordHelper;

    @Autowired
    private SysManagerUserMapper managerUserMapper;

    @Autowired
    private MjProjectMapper projectMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private PermissionManagerService permissionManagerService;

    public APPResultMessage<Object, ManagerAdminUserDTO> getAdminUserList(Integer pageNum, Integer pageSize, String keyword, Date startTime, Date endTime,
                                                                          String roleId, Short status) {
        String[] roleIds = null;
        if (StringUtil.isNotBlank(roleId)){
            roleIds = roleId.split(",");
        }
        if (pageNum != null && pageSize != null){
            PageHelper.startPage(pageNum,pageSize);
            List<ManagerAdminUserDTO> users = managerUserMapper.selectListByKeyword(keyword, startTime, endTime,roleIds,status);
            PageInfo<ManagerAdminUserDTO> tables = new PageInfo<>(users);
            for (ManagerAdminUserDTO dto : tables.getList()){
                if (StringUtil.isNotBlank(dto.getRoleId())){
                    dto.setRoleName(StringUtils.join(roleMapper.selectRoleNameByRoleId(dto.getRoleId().split(",")), ","));
                }
            }
            ResultMessage result = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
            APPResultMessage<Object, ManagerAdminUserDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }else {
            List<ManagerAdminUserDTO> users = managerUserMapper.selectListByKeyword(keyword, startTime, endTime,roleIds,status);
            for (ManagerAdminUserDTO dto : users){
                if (StringUtil.isNotBlank(dto.getRoleId())){
                    dto.setRoleName(StringUtils.join(roleMapper.selectRoleNameByRoleId(dto.getRoleId().split(",")), ","));
                }
            }
            ResultMessage resultMessage = ResultMessage.builder().setList(users);
            APPResultMessage<Object, ManagerAdminUserDTO> successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        }
    }


    public APPResultMessage doAddAdminUser(String password, String username, String roleId) {
        SysManagerUser user = new SysManagerUser();
        user.setUsername(username);
        user.setStatus((short) 1);
        user.setCreateTime(new Date());
        user.setAccount(username);
        user.setRoleId(roleId);
        user.setPassword(password);
        passwordHelper.encryptPasswordManagerUser(user);
        managerUserMapper.insertSelective(user);
        permissionManagerService.doUpdateRedisRoleUser(roleId);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage getManagerUserMsg(int userId) {
        Map map = new HashMap();
        SysManagerUser managerUser = managerUserMapper.selectByPrimaryKey(userId);
        map.put("username", managerUser.getUsername());
        ResultMessage resultMessage = ResultMessage.builder().setData(map);
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        successMessage.setResult(resultMessage);
        return successMessage;
    }


    public APPResultMessage doUpAdminUser(int userId, String username, String roleId, String password) {
        if (StringUtil.isNotBlank(username) || null != roleId){
            managerUserMapper.updateMsgById(userId,username,roleId);
            projectMapper.updatePermissionNameByPermissionId(userId, username);
            permissionManagerService.doUpdateRedisRoleUser(roleId);
        }
        if (StringUtil.isNotBlank(password)){
            SysManagerUser managerUser = managerUserMapper.selectByPrimaryKey(userId);
            managerUser.setPassword(password);
            passwordHelper.encryptPasswordManagerUser(managerUser);
            managerUserMapper.updateByPrimaryKeySelective(managerUser);
        }
        return APPResultMessage.getSuccessMessage();
    }


    public APPResultMessage doUpAdminUserPassword(int userId, String password) {
        SysManagerUser managerUser = managerUserMapper.selectByPrimaryKey(userId);
        managerUser.setPassword(password);
        passwordHelper.encryptPasswordManagerUser(managerUser);
        managerUserMapper.updateByPrimaryKeySelective(managerUser);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doUpAdminUserStatus(String userIds, short status) {
        String[] ids = userIds.split(",");
        managerUserMapper.updateStatusById(ids,status);
        if (status == 10){
            List<Integer> roleIds = managerUserMapper.selectCountRoleIdByIds(ids);
            for (Integer roleId : roleIds){
                String roleUserNumHeader = GlobalStatic.role_user_num + roleId;
                RedisUtil.setCacheIncrementLong(roleUserNumHeader, -1l);
                Long roleUserNum = RedisUtil.getSetCacheIncrementLong(roleUserNumHeader, 0l);
                if (roleUserNum.longValue() == 0l) {
                    int i = managerUserMapper.countByRoleId(roleId);
                    RedisUtil.setCacheIncrement(roleUserNumHeader, i);
                }
            }
        }
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doUpdateUserLastTime(int userId) {
        managerUserMapper.updateLastTimeById(userId);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doBindNormalUser(Integer userId, Integer appUserId) {
        SysManagerUser managerUser = managerUserMapper.selectMsgByBindUserId(appUserId);
        if (managerUser != null && managerUser.getId() != userId){
            return new APPResultMessage(6001,"该账户已被绑定");
        }
        managerUserMapper.updateAppUserIdByUserId(userId,appUserId);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage getChooseAdminUserList(String roleId) {
        String[] roleIds = null;
        if (StringUtil.isNotBlank(roleId)){
            roleIds = roleId.split(",");
        }
        Map<String, List> roleMap = new HashMap();
        for (String s : roleIds){
            List<ManagerAdminUserDTO> list = new ArrayList<>();
            roleMap.put(s, list);
        }
        List<ManagerAdminUserDTO> users = managerUserMapper.selectChooseListByKeyword(roleIds);
        for (ManagerAdminUserDTO dto : users){
            if (StringUtil.isNotBlank(dto.getRoleId())){
                dto.setRoleName(StringUtils.join(roleMapper.selectRoleNameByRoleId(dto.getRoleId().split(",")), ","));
            }
            String[] split = dto.getRoleId().split(",");
            for (String s : split){
                if (roleMap.containsKey(s)){
                    List<ManagerAdminUserDTO> list = roleMap.get(s);
                    list.add(dto);
                    roleMap.put(s, list);
                }
            }
        }
        ResultMessage resultMessage = ResultMessage.builder().setData(roleMap);
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        successMessage.setResult(resultMessage);
        return successMessage;
    }
}
